package com.xiubai.appforpda.activitys;

import android.app.Dialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.xiubai.appforpda.R;
import com.xiubai.appforpda.db.DatabaseUtils;
import com.xiubai.appforpda.entity.BaseEntity;
import com.xiubai.appforpda.entity.SQLMainPamInventBean;
import com.xiubai.appforpda.entity.SQLNCGetUseBean;
import com.xiubai.appforpda.entity.SQLOrgPersonBean;
import com.xiubai.appforpda.entity.SQLOrgStructureBean;
import com.xiubai.appforpda.entity.SQLPamAssetBean;
import com.xiubai.appforpda.entity.SQLPamInvenBean;
import com.xiubai.appforpda.entity.SQLPamLocationBean;
import com.xiubai.appforpda.entity.SQLPamStatusBean;
import com.xiubai.appforpda.entity.WebAssetEntity;
import com.xiubai.appforpda.entity.WebLocationEntity;
import com.xiubai.appforpda.entity.WebMainPamInventEntity;
import com.xiubai.appforpda.entity.WebNCGetUseEntity;
import com.xiubai.appforpda.entity.WebOrgStructureEntity;
import com.xiubai.appforpda.entity.WebPamInventEntity;
import com.xiubai.appforpda.entity.WebPamStatusEntity;
import com.xiubai.appforpda.entity.WebPersonEntity;
import com.xiubai.appforpda.jack.utils.AppConstants;
import com.xiubai.appforpda.jack.utils.JsonParser;
import com.xiubai.appforpda.jack.utils.SharedPreferenceTool;
import com.xiubai.appforpda.jack.utils.Trace;
import com.xiubai.appforpda.jack.utils.Utils;
import com.xiubai.appforpda.jack.utils.WebServiceDataUtils;
import com.xiubai.appforpda.listener.NoDoubleClickListener;
import com.xiubai.appforpda.utils.DisplayUtil;
import com.xiubai.appforpda.webutils.WebServiceHelper;
import com.xiubai.appforpda.widget.CustomDialog;
import com.xiubai.appforpda.widget.CustomDialogListener;

import org.ksoap2.serialization.SoapObject;

import java.net.InetAddress;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author: r3562939
 * @version: V1.0
 * @project: AppForPda
 * @description: description
 * @date: 2018/11/13
 * @time: 13:09
 */
public class TestLoginActivity extends BaseActivity implements View.OnClickListener {

    private EditText et_ip;
    //    private EditText et_port;
    private View btn_confirm;
    private String ip;
    private String code;
    private String dept_code;
    private CustomDialog progressDialog;
//    private String port;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_login);
        initView();
        initData();
    }

    private void initData() {
        String user = SharedPreferenceTool.getInstance().getString(AppConstants.USER);
        if (!TextUtils.isEmpty(user)) {
            et_ip.setText(user);
            et_ip.setSelection(user.length());
        }
        /*String port = SharedPreferenceTool.getInstance().getString(AppConstants.PORT);
        if (!TextUtils.isEmpty(port)) {
            et_port.setText(port);
            et_port.setSelection(port.length());
        }*/
    }

    private void initView() {
        et_ip = (EditText) findViewById(R.id.et_ip);
//        et_port = (EditText) findViewById(R.id.et_port);
        et_ip.setRawInputType(Configuration.KEYBOARD_QWERTY);
//        et_port.setRawInputType(Configuration.KEYBOARD_QWERTY);
        btn_confirm = findViewById(R.id.btn_confirm);
        btn_confirm.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_confirm:
                ip = et_ip.getText().toString();
//                port = et_port.getText().toString();
                if (TextUtils.isEmpty(ip)) {
                    Toast.makeText(this, "工号不能为空!", Toast.LENGTH_SHORT).show();
                    return;
                }
                SharedPreferenceTool.getInstance().saveString(AppConstants.USER, ip);
                doLogin();
                break;
        }
    }

    private boolean checkIp(String ip) {
        boolean is = true;
        try {
            InetAddress.getByName(ip);
        } catch (Exception e) {
            is = false;
        }
        return is;
    }

    private void doLogin() {
        if (!Utils.checkNetworkIsAvailable()) {
            enterHome();
            return;
        }
        String ip = SharedPreferenceTool.getInstance().getString(AppConstants.IP);
        String port = SharedPreferenceTool.getInstance().getString(AppConstants.PORT);
        if (TextUtils.isEmpty(ip) || TextUtils.isEmpty(port)) {
            Toast.makeText(this, "请先到设置界面初始化IP和端口号!", Toast.LENGTH_SHORT).show();
            return;
        }
        showProgressDialog("登录中...");
        String user = SharedPreferenceTool.getInstance().getString(AppConstants.USER);
        List<SQLOrgPersonBean> psncode = DatabaseUtils.getHelper().queryByArgs(SQLOrgPersonBean.class, "psncode", user);
        String name = null;
        if (null == psncode) {
            Toast.makeText(this, "没有匹配到员工账号!", Toast.LENGTH_SHORT).show();
            dialogDismiss(progressDialog);
            return;
        }
        for (SQLOrgPersonBean bean : psncode) {
            name = bean.psnname;
            dept_code = bean.deptcode;
            code = bean.psncode;
            Trace.d("======" + name);
        }

        AppConstants.USER_NAME = name;
        AppConstants.USER_CODE = code;
        AppConstants.DEPT_CODE = dept_code;

//        if (SettingActivity.ALREADY_SYNC) {
//            enterHome();
//        } else {
//            getData();
//        }

//        ActivityStackManager.getInstance().finishActivity(MainActivity.class);
    }

    private void enterHome() {
        Intent intent = new Intent(TestLoginActivity.this, HomeActivity.class);
        startActivity(intent);
        finish();
    }

    private void getData() {
        Message message = Message.obtain();
        message.what = 0;
        message.obj = AppConstants.GET_ORG_DEPT;
        handler.sendMessage(message);
    }

    private static final int GET_ORG = 0;
    private int count;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_ORG:
                    String url = (String) msg.obj;
                    callWS(url);
                    break;
            }
        }
    };

    private void callWS(String url) {
        Trace.d("url====" + url);
        //通过工具类调用WebService接口
        LinkedHashMap<String, String> value = WebServiceDataUtils.getParameterData(url, "1=1");
        WebServiceHelper.callWebService(WebServiceHelper.WEB_URL, AppConstants.METHOD_NAME, value, new WebServiceHelper.WebServiceCallBack() {
            @Override
            public void callBack(SoapObject result) {
                Trace.d("result==" + result);
                if (result != null) {
                    String json = result.getProperty(0).toString();
                    Trace.d("json====" + json);
                    BaseEntity assetBean = JsonParser.deserializeByJson(json, BaseEntity.class);
                    if (assetBean != null) {
                        if (assetBean.isSuccess()) {
                            // do something
                            Trace.d("成功!");
                            count++;
                            Message message = Message.obtain();
                            message.what = 0;
                            switch (count) {
                                case 1:
                                    WebOrgStructureEntity webOrgStructureEntity = JsonParser.deserializeByJson(json, WebOrgStructureEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLOrgStructureBean.class);
                                    DatabaseUtils.getHelper().saveAll(webOrgStructureEntity.getV_org_dept());
                                    message.obj = AppConstants.GET_PERSON;
                                    break;
                                case 2:
                                    WebPersonEntity webPersonEntity = JsonParser.deserializeByJson(json, WebPersonEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLOrgPersonBean.class);
                                    DatabaseUtils.getHelper().saveAll(webPersonEntity.getOrg_psn());
                                    message.obj = AppConstants.GET_PAM_LOCATION;
                                    break;
                                case 3:
                                    WebLocationEntity webLocationEntity = JsonParser.deserializeByJson(json, WebLocationEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLPamLocationBean.class);
                                    DatabaseUtils.getHelper().saveAll(webLocationEntity.getPam_loc());
                                    message.obj = AppConstants.GET_PAM_STATUS;
                                    break;
                                case 4:
                                    WebPamStatusEntity pamStatusBean = JsonParser.deserializeByJson(json, WebPamStatusEntity.class);
                                    DatabaseUtils.getHelper().clear(SQLPamStatusBean.class);
                                    DatabaseUtils.getHelper().saveAll(pamStatusBean.getPam_sta());
                                    enterHome();
                                    break;
                            }
                            if (count >= 4) {
                                return;
                            }
                            handler.sendMessage(message);
                        } else {
                            dialogDismiss(progressDialog);
                            enterHome();
                            Toast.makeText(TestLoginActivity.this, "失败" + assetBean.status + "原因" + assetBean.msg, Toast.LENGTH_SHORT).show();
                        }
                    }
                } else {
                    dialogDismiss(progressDialog);
                    enterHome();
                    if (Utils.checkNetworkIsAvailable()) {
                        Toast.makeText(TestLoginActivity.this, "网络请求失败!", Toast.LENGTH_SHORT).show();
                    }
                }

            }
        });
    }

    /**
     * 显示抓取提示
     */
    private void showProgressDialog(String message) {
        progressDialog = new CustomDialog(this, new CustomDialogListener() {
            @Override
            public void onDialogClosed(int closeType) {

            }
        });
        progressDialog.setView(LayoutInflater.from(this).inflate(R.layout.promt_data_input_layout, null));
        TextView tv_input = (TextView) progressDialog.findId(R.id.tv_input_promt);
        if (tv_input != null) {
            tv_input.setText(message);
        }
        progressDialog.setCanceledOutside(false);
        progressDialog.setCancelable(false);
        progressDialog.show();

        dialogMatchWindow(progressDialog);
    }

    private void dialogMatchWindow(Dialog dialog) {
        Window window = dialog.getWindow();
        window.setGravity(Gravity.CENTER);
        window.getDecorView().setPadding(0, 0, 0, 0);

        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = DisplayUtil.dip2px(300, this.getResources().getDisplayMetrics().density);
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);

    }


    private void dialogDismiss(Dialog dialog) {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }


}
